package com.aube.plugin.rank;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;

import com.aube.plugin.rank.model.RankAppShare;
import com.huyn.baseframework.ImageLoader;
import com.huyn.baseframework.share.ShareModule;
import com.huyn.baseframework.share.ShareType;
import com.huyn.baseframework.share.WeiboUtil;
import com.huyn.baseframework.utils.StorageUtil;
import com.huyn.baseframework.utils.StringUtils;
import com.huyn.baseframework.utils.Utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by huyaonan on 16/8/16.
 */
public class RankShareHelper {

    private Context context;
    private RankAppShare mShareData;
    private IShareBitmapListener mListener;
    private String mShareWeiboImgPath, mShareWechatImgPath;

    public RankShareHelper(Context context, RankAppShare mShareData, IShareBitmapListener listener) {
        this.context = context;
        this.mShareData = mShareData;
        this.mListener = listener;
    }

    public void preloadImg() {
        if(mShareData != null) {
            if(StringUtils.isNotBlank(mShareData.weiboPicUrl)) {
                if (StringUtils.isNotBlank(mShareWeiboImgPath))
                    return;
                ImageLoader.getInstance(context).preloadBitmapToFile(mShareData.weiboPicUrl, new ImageLoader.IPreloadCallback<String>() {
                    @Override
                    public void onSuccess(String s) {
                        if (StringUtils.isNotBlank(s)) {
                            mShareWeiboImgPath = s;
                        }
                    }

                    @Override
                    public void onFail() {

                    }
                });
            }
            if(StringUtils.isNotBlank(mShareData.picurl)) {
                if (StringUtils.isNotBlank(mShareWechatImgPath))
                    return;
                ImageLoader.getInstance(context).preloadBitmapToFile(mShareData.picurl, 250, 250, new ImageLoader.IPreloadCallback<String>() {
                    @Override
                    public void onSuccess(String s) {
                        if (StringUtils.isNotBlank(s)) {
                            mShareWechatImgPath = s;
                        }
                    }

                    @Override
                    public void onFail() {

                    }
                });
            }
        }
    }

    public void toShare(final int type) {
        if(shouldRequestPermission())
            return;
        if(type == ShareType.WEIBO) {
            if(StringUtils.isNotBlank(mShareWeiboImgPath)) {
                shareImg(Utils.copyToFile(mShareWeiboImgPath), mShareData.weiboTitle);
                return;
            }
        } else {
            if(StringUtils.isNotBlank(mShareWechatImgPath)) {
                if(mListener != null)
                    mListener.onResponse(type, Utils.copyToFile(mShareWechatImgPath));
                return;
            }
        }
        Utils.showToast(context, "分享数据有误");
    }

    private void shareImg(String path, String content) {
        try {
            ShareModule shareModule = new ShareModule();
            shareModule.imagePath = path;
            shareModule.content = content;
            WeiboUtil.getInstance((Activity) context).startShareImg((Activity) context, shareModule);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Checks whether it is necessary to ask for permission to read storage. If necessary, it also
     * requests permission.
     *
     * @return true if a permission request is made. False if it is not necessary.
     */
    @TargetApi(23)
    private boolean shouldRequestPermission() {
        if (requiresPermission()) {
            ((Activity) context).requestPermissions(new String[] {Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
            Utils.showToast(context, "文件文法访问,请先在应用程序设置中打开存储权限");
            return true;
        } else {
            return false;
        }
    }

    @TargetApi(23)
    private boolean requiresPermission() {
        return StorageUtil.SDK_INT >= 23
                && context.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED;
    }

    private String storeToFile(String src, Bitmap bitmap) {
        File f = new File(src);
        FileOutputStream fOut = null;
        if(!f.getParentFile().exists())
            f.getParentFile().mkdirs();
        try {
            f.createNewFile();
            fOut = new FileOutputStream(f);

            //不压缩和只压缩一点大小相差巨大！
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fOut);

            fOut.flush();
            return src;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if(fOut!=null) {
                try {
                    fOut.close();
                } catch (IOException e) {
                }
            }
        }
    }

    public interface IShareBitmapListener {
        public void onResponse(int type, String path);
    }

}
